﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;

namespace SmallSpider.Class
{
    public class HttpContent
    {
        public string GetPageData(string url, ref string charSet)
        {
            string strWebData = string.Empty;
            if (url != null || url.Trim() != "")
            {
                WebClient myWebClient = new WebClient();
                //创建WebClient实例myWebClient
                // 需要注意的：
                //有的网页可能下不下来，有种种原因比如需要cookie,编码问题等等
                //这是就要具体问题具体分析比如在头部加入cookie
                // webclient.Headers.Add("Cookie", cookie);
                //这样可能需要一些重载方法。根据需要写就可以了
                //获取或设置用于对向 Internet 资源的请求进行身份验证的网络凭据。
                myWebClient.Credentials = CredentialCache.DefaultCredentials;
                //如果服务器要验证用户名,密码
                //NetworkCredential mycred = new NetworkCredential(struser, strpassword);
                //myWebClient.Credentials = mycred;
                //从资源下载数据并返回字节数组。（加@是因为网址中间有"/"符号）
                byte[] myDataBuffer;
                try
                {
                    myDataBuffer = myWebClient.DownloadData(url);
                }
                catch
                {
                    return string.Empty;
                }
                strWebData = Encoding.Default.GetString(myDataBuffer);
                //获取网页字符编码描述信息
                string webCharSet = string.Empty;
                webCharSet = GetHtmlCharSet(strWebData);
                webCharSet = webCharSet.Replace("\"", "");
                webCharSet = webCharSet.Replace("'", "");
                if (charSet == null || charSet == "")
                {
                    //如果未获取到编码，则设置默认编码
                    if (webCharSet == null || webCharSet == "")
                    {
                        charSet = "utf-8";
                    }
                    else
                    {
                        charSet = webCharSet;
                    }
                }
                try
                {
                    if (charSet != null && charSet != "" && Encoding.GetEncoding(charSet) != Encoding.Default)
                    {
                        strWebData = Encoding.GetEncoding(charSet).GetString(myDataBuffer);
                    }
                }
                catch
                {
                    charSet = "utf-8";
                    strWebData = Encoding.GetEncoding(charSet).GetString(myDataBuffer);
                }
            }
            return strWebData;
        }

        public string GetHtmlCharSet(string strHtmlContent)
        {
            string strCharSet = string.Empty;

            Match charSetMatch = Regex.Match(strHtmlContent, "<meta([^<]*)charset=([^<]*); IE=", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            strCharSet = charSetMatch.Groups[2].Value;
            if (!string.IsNullOrEmpty(strCharSet)) return strCharSet;

            charSetMatch = Regex.Match(strHtmlContent, "<meta([^<]*)charset=([^<]*)('|\")([^<]*)http-equiv", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            strCharSet = charSetMatch.Groups[2].Value;
            if (!string.IsNullOrEmpty(strCharSet)) return strCharSet;

            charSetMatch = Regex.Match(strHtmlContent, "<meta([^<]*)charset=([^<]*)('|\")", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            strCharSet = charSetMatch.Groups[2].Value;
            return strCharSet;
        }

    }
}
